package com.mkz.core.zookeeper.util;

import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RetryExclusiveLock {
	private InterProcessMutex lock;
	
	public RetryExclusiveLock(CuratorFramework zkCurator, String lockPath) {
		if(!isValidPath(lockPath)) {
			return;
		}
		if(null==zkCurator) {
			log.error("Curator初始化异常NULL，错误代码 929！");
		}
		lock = new InterProcessMutex(zkCurator, lockPath);
	}

	//获取排他锁
	public boolean lock() {
		Boolean result = false;
		try {
			result = lock.acquire(2, TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("获取分布式锁时抛出异常，错误代码 909！");
			e.printStackTrace();
		}
		return result;
	}
	//释放排他锁
	public void release(){
		try {
			if(null!=lock){
				lock.release();
			}
		} catch (Exception e) {
			log.error("释放分布式锁时抛出异常，错误代码 909！");
			e.printStackTrace();
		}
	}
	
	//判断节点路径是否合法
	public boolean isValidPath(String absolutePath){
		if(StrUtil.isBlank(absolutePath)){
			log.error("传入的路径为空，错误代码 901！");
			return false;
		}
		if(!absolutePath.startsWith("/")){
			log.error("传入的路径必须以'/'开头，错误代码 902！");
			return false;
		}
		if(absolutePath.endsWith("/")){
			log.error("传入的路径不能以'/'结尾，错误代码 903！");
			return false;
		}
		if("/".equals(absolutePath)){
			log.error("传入的路径没有节点，错误代码 904！");
			return false;
		}
		return true;
	}
}
